clear all;
close all;

%  =======================================================================================================================================================
% 
%  Code Description: 
%  This codefile runs the model in Section 4 as well as the sensitivity analysis provided in the internet appendix C.2. 
% 
%  =======================================================================================================================================================
% 
%  Major output:
%  - model results at the sector-, fund- and security-level
%
%  =======================================================================================================================================================
% 
%  General disclaimer:
%  This file directory produces replication code for "Connected Funds". 
%  Because we cannot share the underlying data provided by the Bundesbank's Research Data and Service Centre (RDSC) and other subscription data sources, 
%  we have included pseudo data to show how the raw data are formatted.
%  Other researchers can go through a similar approval and subscription process to obtain the underlying data. (2023-04-06)
% 
%  =======================================================================================================================================================

projectPath = 'C:\ConnectedFunds_Codebase\'

% Add functions folders
addpath(strcat(projectPath, 'Code\matlab_functions'));

%%  ======================================================= Plug in model parameters as estimated in ... =================================================

... Model_Part_1_Initial Shock_Estimation
... Model_Part_2a_Non_Flow_Driven_Channel_Prepare_Data
... Model_Part_2b_Non-flow-driven Channel_Estimation
... Model_Part_3_Flow-driven Channel_Estimation
... and shown in Table 7: Overview of the main model parameters.

save_assetLevel = 1;

shock_bonds5     = -0.0159;
shock_equities5  = -0.0841;

delta_log_vix5   = 0.375;

Amihud_CorpBonds = 10^-8;
Amihud_SovBonds  = 5*(10^-9);
Amihud_Equities  = 10^-9;

gamma_pub  = 0.1389;
gamma_pub1 = 0.2287;
gamma_pub2 = 0.2327;
gamma_pub3 = 0.1018;
gamma_pub7 = 0.0673;

gamma_spez = 0;
gamma_spez1 = 0;
gamma_spez2 = 0;
gamma_spez3 = 0;
gamma_spez7 = 0;

beta_pub   = 0.0246;
beta_pub1 = 0.0181;
beta_pub2 = 0.0273;
beta_pub3 = 0.0289;
beta_pub7 = 0.0321;

beta_spez  = 0.0263;
beta_spez1 = 0;
beta_spez2 = 0;
beta_spez3 = 0;
beta_spez7 = 0;

theta_pub  = -0.0262;
theta_pub1 = -0.0144;
theta_pub2 = 0;
theta_pub3 = -0.0381;
theta_pub7 = -0.0415;

theta_spez = -0.0246;
theta_spez1 = -0.0192;
theta_spez2 = -0.0156;
theta_spez3 = -0.0282;
theta_spez7 = -0.0212;

% Set factor range for sensitivity analysis
factor = (0.5:0.1:2);

%%  ================================================================ Preparations ======================================================================

% Load fund-level data
load(strcat(projectpath, 'Data\IFS\IFS_All_CleanData.mat'))
clear date_index fundid


IFS_All(IFS_All.artmittel == 4, :) = [];
IFS_All(IFS_All.artmittel == 6, :) = [];
IFS_All(IFS_All.artmittel > 7, :) = [];
IFS_All(IFS_All.etf == 1, :) = [];

ufund_all = unique(IFS_All.ISIN);

% Generate results matrices
Results_FundSystemicness5 = NaN(length(umonth),length(ufund_all));
Results_FundSystemicness5_CrossFund = NaN(length(umonth),length(ufund_all));
Results_FundSystemicness5_Direct = NaN(length(umonth),length(ufund_all));
Results_FundReturn5 = NaN(length(umonth),length(ufund_all));
Results_FundInitialShock5 = NaN(length(umonth),length(ufund_all));
Results_FundTotalLoss5 = NaN(length(umonth),length(ufund_all));
Results_FundLossCross5 = NaN(length(umonth),length(ufund_all));
Results_FundLossDirect5 = NaN(length(umonth),length(ufund_all));

Results_Lookthrough_FundSystemicness5 = NaN(length(umonth),length(ufund_all));
Results_Lookthrough_FundSystemicness5_CrossFund = NaN(length(umonth),length(ufund_all));
Results_Lookthrough_FundSystemicness5_Direct = NaN(length(umonth),length(ufund_all));
Results_Lookthrough_FundReturn5 = NaN(length(umonth),length(ufund_all));
Results_Lookthrough_FundInitialShock5 = NaN(length(umonth),length(ufund_all));
Results_Lookthrough_FundTotalLoss5 = NaN(length(umonth),length(ufund_all));
Results_Lookthrough_FundLossCross5 = NaN(length(umonth),length(ufund_all));
Results_Lookthrough_FundLossDirect5 = NaN(length(umonth),length(ufund_all));

Results_FundMKT = NaN(length(umonth),length(ufund_all));
Results_FundMKT_Equities= NaN(length(umonth),length(ufund_all));
Results_FundMKT_CorpBonds= NaN(length(umonth),length(ufund_all));
Results_FundMKT_SovBonds= NaN(length(umonth),length(ufund_all));
Results_FundMKT_Cash= NaN(length(umonth),length(ufund_all));
Results_FundFund_Holds= NaN(length(umonth),length(ufund_all));
Results_FundFund_HeldBy= NaN(length(umonth),length(ufund_all));
Results_FundOtherAssets= NaN(length(umonth),length(ufund_all));
Results_FundFund_HoldsNumber = NaN(length(umonth),length(ufund_all));
Results_Fund_TotalHoldings = NaN(length(umonth),length(ufund_all));
Results_Fund_Lookthrough_TotalHoldings = NaN(length(umonth),length(ufund_all));


%%  ================================================================ Run stresstest model (loop over sample period) ======================================================================

for t = length(umonth) : -1 : 1 
    
    date = umonth(t)

    % Get fund-level characteristics in month t
    IFS_All_t                                   = IFS_All(IFS_All.DATUM == date,:);
    IFS_All_t(IFS_All_t.BANKG <= 0, :)          = [];
    IFS_All_t(IFS_All_t.bilanzsumme <= 0, :)    = [];
    IFS_All_t(isnan(IFS_All_t.bilanzsumme), :)  = [];
    IFS_All_t                                   = sortrows(IFS_All_t,'ISIN','ascend');

    % Load funds' contemporary portfolio holdings
    load(strcat(projectPath, 'Data\IFS\mat\IFS_Holdings_', num2str(date), '.mat'));
    
    IFS_Holdings(IFS_Holdings.AMOUNT<=0,:) = [];  
    
    ufund =  intersect(IFS_Holdings.ISIN,IFS_All_t.ISIN); 

    [~,idx]             = ismember(IFS_All_t.ISIN,ufund);
    IFS_All_t(idx==0,:) = [];

    [~,idx2_a]                    = ismember(IFS_Holdings.ISIN,ufund);
    IFS_Holdings(idx2_a == 0, : ) = [];
    
    uasset = unique(IFS_Holdings.SECCODE);

    clear idx*

    %%% Generate cross-fund network
    [~,idx2_a] = ismember(IFS_Holdings.ISIN,ufund);
    [~,idx2_b] = ismember(IFS_Holdings.SECCODE,uasset);

    Network = accumarray([idx2_a idx2_b],IFS_Holdings.AMOUNT,[length(ufund) length(uasset)]);

    [~,idx]               = ismember(ufund,uasset);
    Network_Fund          = zeros(length(ufund));
    Network_Fund(:,idx>0) = Network(:,idx(idx>0));

    % Generate asset network
    Network(:,idx(idx>0)) = [];
    uasset(idx(idx>0))    = [];

    clear idx; 

    cash              = IFS_All_t.BANKG;
    fund              = sum(Network_Fund')';
    isin              = IFS_All_t.ISIN;
    totalassets       = IFS_All_t.bilanzsumme; 
    artmittel         = IFS_All_t.artmittel;
    spezial           = IFS_All_t.SPEZIAL;
    
    % Compute vector of "other assets"
    OtherAssets                = totalassets  - sum(Network')' - sum(Network_Fund')';
    OtherAssets(OtherAssets<0) = 0;
    
    % Load CSDB data on securities
    if t > 1
        load(strcat(projectPath, 'Data\CSDB\mat\CSDB_', num2str(umonth(t-1)), '.mat'));
    else
        load(strcat(projectPath, 'Data\CSDB\mat\CSDB_', num2str(umonth(t)), '.mat'));
    end

    CSDB = sortrows(CSDB,'ISIN','ascend');
    
    [~,idx] = ismember(uasset,CSDB.ISIN);
    
    AssetType = zeros(length(uasset),1);
    AssetType(idx>0) = 1*startsWith(CSDB.ESA_INS_1995(idx(idx>0)),'F.3') + ...
                       2*startsWith(CSDB.ESA_INS_1995(idx(idx>0)),'F.51') + ...
                       3*startsWith(CSDB.ESA_INS_1995(idx(idx>0)),'F.52');
    
    Sovereign = zeros(length(uasset),1);
    Sovereign(idx>0) = 1*startsWith(CSDB.ESA_ISSUER_1995(idx(idx>0)),'S.13');
       
    % Move assets with unknown type to category "other assets"
    i = find(AssetType == 0);
    OtherAssets = OtherAssets + sum(Network(:,i)')';
    Network(:,i) = [];
    AssetType(i) = []; Sovereign(i) = [];
    uasset(i) = [];
    
    % Move foreign fund shares to category "other assets"
    i = find(AssetType == 3);
    OtherAssets = OtherAssets + sum(Network(:,i)')';
    Network(:,i) = [];
    AssetType(i) = []; Sovereign(i) = [];
    uasset(i) = [];
    
    % Load model parameter vectors
    PriceImpact = zeros(length(uasset),1);
    PriceImpact(AssetType == 1 & Sovereign == 0) = Amihud_CorpBonds;
    PriceImpact(AssetType == 1 & Sovereign == 1) = Amihud_SovBonds;
    PriceImpact(AssetType == 2)                  = Amihud_Equities;
    
    Gamma = zeros(length(ufund),1);
    Gamma(spezial == 0 & artmittel == 1 ) = gamma_pub1;
    Gamma(spezial == 0 & artmittel == 2 ) = gamma_pub2;
    Gamma(spezial == 0 & artmittel == 3 ) = gamma_pub3;
    Gamma(spezial == 0 & artmittel == 7 ) = gamma_pub7;
        
    Gamma(spezial == 1 & artmittel == 1 ) = gamma_spez1;
    Gamma(spezial == 1 & artmittel == 2 ) = gamma_spez2;
    Gamma(spezial == 1 & artmittel == 3 ) = gamma_spez3;
    Gamma(spezial == 1 & artmittel == 7 ) = gamma_spez7;
    
    Beta = zeros(length(ufund),1);
    Beta(spezial == 0 & artmittel == 1 ) = beta_pub1;
    Beta(spezial == 0 & artmittel == 2 ) = beta_pub2;
    Beta(spezial == 0 & artmittel == 3 ) = beta_pub3;
    Beta(spezial == 0 & artmittel == 7 ) = beta_pub7;
        
    Beta(spezial == 1 & artmittel == 1 ) = beta_spez1;
    Beta(spezial == 1 & artmittel == 2 ) = beta_spez2;
    Beta(spezial == 1 & artmittel == 3 ) = beta_spez3;
    Beta(spezial == 1 & artmittel == 7 ) = beta_spez7;
    
    Theta = zeros(length(ufund),1);
    Theta(spezial == 0 & artmittel == 1 ) = theta_pub1;
    Theta(spezial == 0 & artmittel == 2 ) = theta_pub2;
    Theta(spezial == 0 & artmittel == 3 ) = theta_pub3;
    Theta(spezial == 0 & artmittel == 7 ) = theta_pub7;
        
    Theta(spezial == 1 & artmittel == 1 ) = theta_spez1;
    Theta(spezial == 1 & artmittel == 2 ) = theta_spez2;
    Theta(spezial == 1 & artmittel == 3 ) = theta_spez3;
    Theta(spezial == 1 & artmittel == 7 ) = theta_spez7;
    
    % Add cash
    NetworkWithCash = [Network cash];
    PriceImpact(end+1,1) = 0;
    AssetType(end+1,1) = 0;
    
    % Generate portfolio shares matrix M
    M = NetworkWithCash./repmat(sum(NetworkWithCash')',1,size(NetworkWithCash,2));
    
    % Express (sub-)portfolio holdings matrices in € (data comes in units of €T)
    NetworkWithCash = 1000*NetworkWithCash;
    Network_Fund    = 1000*Network_Fund;
    OtherAssets     = 1000*OtherAssets;

    % Generate leverage vector
    Leverage = IFS_All_t.bilanzsumme./IFS_All_t.FONDSVERM - 1;
    
    % Load initial shock vector (shocks on marketable assets and VIX)
    F_MKT = zeros(length(uasset)+1,1);
    F_MKT(AssetType == 1) = shock_bonds5;
    F_MKT(AssetType == 2) = shock_equities5;
    F_OtherAssets = 0;
    delta_log_vix = delta_log_vix5;
    
    % Compute aggregate vulnerability (AV)
    [AV0,AV,initialShock,initialShock_i,Return_i,Loss_i,S,Return_j,LiquidationVolume_j] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, Beta, Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix, 1, 0);
    
    % Save aggregate results
    Results_AV5(t,:) = AV;
    Results_InitialShock5(t,:) = initialShock;
    Results_AV_CrossHoldings5(t,:) = sum(AV(3:end))/AV(1);
    Results_AV_FlowDiscretionary5(t,:) = AV0;
    
    % Save fund-level results
    [~,idxWhereFund] = ismember(ufund,ufund_all);
    Results_FundSystemicness5(t,idxWhereFund) = S(:,1);
    Results_FundSystemicness5_CrossFund(t,idxWhereFund) = S(:,2);
    Results_FundSystemicness5_Direct(t,idxWhereFund) = S(:,3);
    Results_FundReturn5(t,idxWhereFund) = Return_i;
    Results_FundInitialShock5(t,idxWhereFund) = initialShock_i;
    Results_FundTotalLoss5(t,idxWhereFund) = sum(Loss_i')';
    Results_FundLossCross5(t,idxWhereFund) = Loss_i(:,1) + Loss_i(:,3) + Loss_i(:,4);
    Results_FundLossDirect5(t,idxWhereFund) = Loss_i(:,2);
    
    % Alternative: drop cross-fund holdings and scale up direct holdings
    % and compute counterfactual AV assuming funds would only hold direct
    % holdings (no fund shares)
    a = sum(Network_Fund')' + OtherAssets + sum(NetworkWithCash')'; 
    b = OtherAssets + sum(NetworkWithCash')'; 
    s = a./b;
    OtherAssets_H0 = s.*OtherAssets;
    NetworkWithCash_H0 = repmat(s,1,size(NetworkWithCash,2)).*NetworkWithCash;
    Network_Fund_H0 = 0*Network_Fund;
    x = log(sum(NetworkWithCash_H0)) - log(sum(NetworkWithCash));
    NetworkWithCash_H0(:,x>1.5) = NetworkWithCash(:,x>1.5);
    
    [AV0_H0,AV_H0,initialShock_H0] = AV_Calculation(OtherAssets_H0, sum(NetworkWithCash_H0')', NetworkWithCash_H0, sum(Network_Fund_H0')', Network_Fund_H0, Leverage, Gamma, Beta, Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix, 1, 1);
    
    Results_AV_H05(t,:)                   = AV_H0;
    Results_InitialShock_H05(t,:)         = initialShock_H0;
    Results_AV_H0_FlowDiscretionary5(t,:) = AV0_H0;
    
    % Do some housekeeping
    clear x a b s OtherAssets_H0 NetworkWithCash_H0 Network_Fund_H0 AV_H0 initialShock_H0 AV0_H0;
    
    % Alternative: Compute counterfactual AV, assuming that funds would use zero leverage
    [AV0_NoLeverage,AV_NoLeverage,initialShock_NoLeverage] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, 0*Leverage, Gamma, Beta, Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix, 1, 1);
    
    Results_AV_NoLeverage5(t,:)                     = AV_NoLeverage;
    Results_InitialShock_NoLeverage5(t,:)           = initialShock_NoLeverage;
    Results_AV_NoLeverage_CrossHoldings5(t,:)       = sum(AV_NoLeverage(3:end))/AV_NoLeverage(1);
    Results_AV_NoLeverage_FlowDiscretionary5(t,:)   = AV0_NoLeverage;
    
    % Alternative: Compute AV assuming that funds would not redeem their
    % fund share holdings
    [AV0b,AVb] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, Beta, Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix, 0, 1);
    
    Results_AV_NoFundLiquidations5(t,:)                     = AVb;
    Results_AV_NoFundLiquidations_FlowDiscretionary5(t,:)   = AV0b;
      
    % Compute AV after portfolio look-through
    [NetworkWithCash_Look,Network_Fund_Look,OtherAssets_Look] = PortfolioLookthrough_ConnFunds_Analytical(NetworkWithCash,Network_Fund,OtherAssets);
    [AV0_Look,AV_Look,initialShock_Look,initialShock_Look_i,Return_Look_i,Loss_Look_i,S_Look,ReturnLook_j,LiquidationVolumeLook_j] = AV_Calculation(OtherAssets_Look, sum(NetworkWithCash_Look')', NetworkWithCash_Look, sum(Network_Fund_Look')', Network_Fund_Look, Leverage, Gamma, Beta, Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix, 1, 0);
    
    Results_Fund_TotalHoldings(t,idxWhereFund) = Results_FundMKT(t,idxWhereFund) + Results_FundFund_Holds(t,idxWhereFund) + Results_FundOtherAssets(t,idxWhereFund);
    
    Results_Lookthrough_AV5(t,:)                    = AV_Look;
    Results_Lookthrough_AV_FlowDiscretionary5(t,:)  = AV0_Look;   
    Results_Lookthrough_InitialShock5(t,:)          = initialShock_Look;
        
    Results_Lookthrough_FundSystemicness5(t,idxWhereFund)           = S_Look(:,1);
    Results_Lookthrough_FundSystemicness5_CrossFund(t,idxWhereFund) = S_Look(:,2);
    Results_Lookthrough_FundSystemicness5_Direct(t,idxWhereFund)    = S_Look(:,3);
    Results_Lookthrough_FundReturn5(t,idxWhereFund)                 = Return_Look_i;
    Results_Lookthrough_FundInitialShock5(t,idxWhereFund)           = initialShock_Look_i;
    Results_Lookthrough_FundTotalLoss5(t,idxWhereFund)              = sum(Loss_Look_i')';
    Results_Lookthrough_FundLossCross5(t,idxWhereFund)              = Loss_Look_i(:,1) + Loss_Look_i(:,3) + Loss_Look_i(:,4);
    Results_Lookthrough_FundLossDirect5(t,idxWhereFund)             = Loss_Look_i(:,2);
    
    Results_FundMKT(t,idxWhereFund)                 = sum(NetworkWithCash')';
    Results_FundMKT_Equities(t,idxWhereFund)        = sum(NetworkWithCash(:,PriceImpact == Amihud_Equities)')';
    Results_FundMKT_CorpBonds(t,idxWhereFund)       = sum(NetworkWithCash(:,PriceImpact == Amihud_CorpBonds)')';
    Results_FundMKT_SovBonds(t,idxWhereFund)        = sum(NetworkWithCash(:,PriceImpact == Amihud_SovBonds)')';
    Results_FundMKT_Cash(t,idxWhereFund)            = sum(NetworkWithCash(:,end))';
    Results_FundFund_Holds(t,idxWhereFund)          = sum(Network_Fund')';
    Results_FundFund_HoldsNumber(t,idxWhereFund)    = sum((Network_Fund>0)')';
    Results_FundFund_HeldBy(t,idxWhereFund)         = sum(Network_Fund)';
    Results_FundOtherAssets(t,idxWhereFund)         = OtherAssets;
    Results_Fund_TotalHoldings(t,idxWhereFund)      = Results_FundMKT(t,idxWhereFund) + Results_FundFund_Holds(t,idxWhereFund) + Results_FundOtherAssets(t,idxWhereFund);
    
    Results_Fund_Lookthrough_TotalHoldings(t,idxWhereFund) = nansum(NetworkWithCash_Look')' + nansum(Network_Fund_Look')' + OtherAssets_Look;
    
    % Save asset-level results
    if save_assetLevel == 1
        date                    = umonth(t);
        totalholdings           = sum(NetworkWithCash)';
        totalholdings_Look      = nansum(NetworkWithCash_Look)';
        tna                     = nansum(Results_Fund_TotalHoldings(t,:));
        tna_Look                = nansum(Results_Fund_Lookthrough_TotalHoldings(t,:));
        save(strcat(projectpath, 'Data\StresstestModel\AssetLevel\Results_',num2str(date)),...
             'date','uasset','AssetType','Sovereign','totalholdings','PriceImpact','Return_j','LiquidationVolume_j','totalholdings_Look','ReturnLook_j','LiquidationVolumeLook_j','tna','tna_Look');
        clear date totalholdings* tna*;
    end
    
    
    %%  =============================================================================== For 2019-12: conduct sensitivity analysis of AV  ==========================================================================

    if umonth(t) == 201912
       
        % Panel 1: PriceImpact
       ResultsSensi_AV_Amihud5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_Amihud5 = NaN(length(factor),1);
       disp('Amihud')
       for f = 1:length(factor)
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, Beta, Theta, factor(f).*PriceImpact, F_MKT, F_OtherAssets, delta_log_vix, 1, 1); 
           ResultsSensi_AV_Amihud5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_Amihud5(f) = sum(AV(3:end))/AV(1);
       end

       % PriceImpact (only bonds --> relative changes)
       ResultsSensi_AV_AmihudBond5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_AmihudBond5 = NaN(length(factor),1);
       disp('Amihud - Bond')
       for f = 1:length(factor)
           tmp_PriceImpact = PriceImpact;
           tmp_PriceImpact(AssetType == 1) = factor(f).*tmp_PriceImpact(AssetType == 1);
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, Beta, Theta, tmp_PriceImpact, F_MKT, F_OtherAssets, delta_log_vix, 1, 1); 
           ResultsSensi_AV_AmihudBond5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_AmihudBond5(f) = sum(AV(3:end))/AV(1);
           clear tmp_PriceImpact;
       end
       
       % Panel 2: Gamma (FPR)
       ResultsSensi_AV_Gamma5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_Gamma5 = NaN(length(factor),1);
       disp('FPR')
       for f = 1:length(factor)
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, factor(f).*Gamma, Beta, Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix,1, 1); 
           ResultsSensi_AV_Gamma5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_Gamma5(f) = sum(AV(3:end))/AV(1);
       end
       
       % Panel 3: Beta (Non-flow: Flow)
       ResultsSensi_AV_Beta5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_Beta5 = NaN(length(factor),1);
       disp('Beta')
       for f = 1:length(factor)
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, factor(f).*Beta, Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix,1, 1); 
           ResultsSensi_AV_Beta5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_Beta5(f) = sum(AV(3:end))/AV(1);
       end
       
       % Panel 4: Theta (Non-flow: VIX)
       ResultsSensi_AV_Theta5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_Theta5 = NaN(length(factor),1);
       disp('Theta')
       for f = 1:length(factor)
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, Beta, factor(f).*Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix,1, 1); 
           ResultsSensi_AV_Theta5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_Theta5(f) = sum(AV(3:end))/AV(1);
       end

       % Alternative: Beta and Theta (Non-flow)
       ResultsSensi_AV_BetaTheta5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_BetaTheta5 = NaN(length(factor),1);
       disp('Beta and Theta')
       for f = 1:length(factor)
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, factor(f).*Beta, factor(f).*Theta, PriceImpact, F_MKT, F_OtherAssets, delta_log_vix,1, 1); 
           ResultsSensi_AV_BetaTheta5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_BetaTheta5(f) = sum(AV(3:end))/AV(1);
       end
       
       % Additional: Initial shock
       ResultsSensi_AV_InitialShock5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_InitialShock5 = NaN(length(factor),1);
       disp('Initial shock')
       for f = 1:length(factor)
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, Gamma, Beta, Theta, PriceImpact, factor(f).*F_MKT, factor(f).*F_OtherAssets, factor(f).*delta_log_vix,1, 1); 
           ResultsSensi_AV_InitialShock5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_InitialShock5(f) = sum(AV(3:end))/AV(1);
       end  
       
       % Additional: All parameters
       ResultsSensi_AV_All5 = NaN(length(factor),5);
       ResultsSensi_AV_CrossHoldings_All5 = NaN(length(factor),1);
       disp('All')
       for f = 1:length(factor)
           [~,AV,~] = AV_Calculation(OtherAssets, sum(NetworkWithCash')', NetworkWithCash, sum(Network_Fund')', Network_Fund, Leverage, factor(f).*Gamma, factor(f).*Beta, factor(f).*Theta, factor(f).*PriceImpact, factor(f).*F_MKT, factor(f).*F_OtherAssets, factor(f).*delta_log_vix,1, 1); 
           ResultsSensi_AV_All5(f,:) = AV;
           ResultsSensi_AV_CrossHoldings_All5(f) = sum(AV(3:end))/AV(1);
       end 
    end
        
end

clear IFS_All t ans artmittel AssetType AV AV0 Beta cash CSDB date f F* fund Gamma i* IFS_* Leverage Loss_i M Network* OtherAssets PriceImpact Return_i S* spezial Theta totalassets uasset ufund;
save(strcat(projectpath, 'Data\StresstestModel\AV_Application_LongSample.mat'));


%%  ===================================================================== Export S and V to run predictive regressions in stata ================================================================

tmp = table(vect(repmat(ufund_all',Tmonth,1)),vect(repmat(umonth,1,length(ufund_all))),...
            Results_FundSystemicness5(:),Results_FundSystemicness5_CrossFund(:),Results_FundSystemicness5_Direct(:),...            
            Results_FundMKT(:),Results_FundFund_Holds(:),Results_FundFund_HeldBy(:),Results_FundOtherAssets(:),Results_FundFund_HoldsNumber(:),Results_Fund_TotalHoldings(:),...
            Results_FundReturn5(:), Results_FundLossCross5(:), Results_FundLossDirect5(:));
        
tmp.Properties.VariableNames{1}  = 'ISIN';
tmp.Properties.VariableNames{2}  = 'DATUM';
tmp.Properties.VariableNames{3}  = 'Systemicness5';
tmp.Properties.VariableNames{4}  = 'Systemicness_CrossFund5';
tmp.Properties.VariableNames{5}  = 'Systemicness_Direct5';
tmp.Properties.VariableNames{6}  = 'Holdings_MKT';
tmp.Properties.VariableNames{7}  = 'Holdings_Fund';
tmp.Properties.VariableNames{8}  = 'HeldBy_Fund';
tmp.Properties.VariableNames{9}  = 'Holdings_Other';
tmp.Properties.VariableNames{10} = 'Holdings_FundNumber';
tmp.Properties.VariableNames{11} = 'Holdings_Total';
tmp.Properties.VariableNames{12} = 'ModelReturn5';
tmp.Properties.VariableNames{13} = 'LossCross5';
tmp.Properties.VariableNames{14} = 'LossDirect5';

tmp(isnan(tmp.Systemicness5),:) = [];

writetable(tmp,strcat(projectpath, 'Data\StresstestModel\Systemicness_ForStata.csv'));